<template>
  <el-dialog
    :visible.sync="isShow"
    :show-close="false"
    width="600px"
    class="register"
    center
  >
    <!-- 表单验证
    1. el-form  model   rules
    2. 在需要验证的项el-form-item上加上一个prop="需要验证的字段名" 
    3. 写验证规则
    rules : {
        prop的绑定值: [
        {required:true,message:错误信息,trigger:"change/blur"},
        {min:最小长度,max:最大长度,message:错误信息,trigger:"change/blur"}
        ]
    }
     -->

    <div slot="title" class="title">用户注册</div>

    <el-form :model="form" label-width="65px" :rules="rules" ref="form">
      <el-form-item label="头像" prop="avatar">
        <el-upload
          class="avatar-uploader"
          :action="baseUrl + '/uploads'"
          name="image"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <img
            v-if="form.avatar"
            :src="baseUrl + '/' + form.avatar"
            class="avatar"
          />
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <el-form-item label="昵称" prop="username">
        <el-input v-model="form.username"> </el-input>
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="form.email"> </el-input>
      </el-form-item>
      <el-form-item label="手机" prop="phone">
        <el-input v-model="form.phone"> </el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="form.password" show-password> </el-input>
      </el-form-item>
      <el-form-item label="图形码" prop="code">
        <el-row>
          <el-col :span="16">
            <el-input v-model="form.code"></el-input>
          </el-col>
          <el-col :span="7" :offset="1">
            <img
              class="code"
              :src="baseUrl + codebase"
              alt=""
              @click="changeCode"
            />
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="验证码" prop="rcode">
        <el-row>
          <el-col :span="16">
            <el-input v-model="form.rcode"></el-input>
          </el-col>
          <el-col :span="7" :offset="1">
            <el-button @click="getPhoneCode" :disabled="num != 5"
              >获取用户验证码<span v-if="num != 5"
                >({{ num }}s)</span
              ></el-button
            >
          </el-col>
        </el-row>
      </el-form-item>
    </el-form>

    <div slot="footer">
      <el-button @click="isShow = false">取消</el-button>
      <el-button type="primary" @click="submit">确认</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { getPhoneCodeApi, getRegisterUser } from "@/api/register.js";
export default {
  /*  侦听器  (watch)
  侦听器： 就是对某个值（通过this访问的值）的change事件
  定义： watch: {
    本质就是一个function
    方法名() {
      方法名： 写出需要侦听的值，去掉this，加上引号 "isShow"
    }
    "$route.query.参数"(newVal, oldVal) {
      newVal： 当前值
      oldVal:  上一刻的值
    }
  }
  
  */

  watch: {
    isShow(newVal) {
      if (newVal == false) {
        // 清空表单
        this.$refs.form.resetFields();
      }
    },
  },

  data() {
    return {
      imageUrl: "",
      isShow: false,
      baseUrl: "",
      codebase: "/captcha?type=sendsms",
      num: 5,

      form: {
        avatar: "", // 是	string	头像地址
        username: "", // 是	string	用户名
        email: "", // 是	string	邮箱
        phone: "", // 是	string	手机号
        password: "", // 是	string	密码
        code: "", // 是	string	验证码
        rcode: "", // 短信验证码
      },
      rules: {
        avatar: [{ required: true, message: "必填", trigger: "change" }],
        username: [{ required: true, message: "必填", trigger: "change" }],
        email: [
          { required: true, message: "必填", trigger: "change" },
          {
            validator: (rule, value, callback) => {
              let _reg = /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/;
              if (_reg.test(value)) {
                callback();
              } else {
                callback(new Error("请输入正确邮箱"));
              }
            },
          },
        ],
        phone: [
          { required: true, message: "必填", trigger: "change" },
          {
            validator: (rule, value, callback) => {
              let _reg = /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/;
              if (_reg.test(value)) {
                callback();
              } else {
                callback(new Error("请输入正确手机号码"));
              }
            },
          },
        ],
        password: [{ required: true, message: "必填", trigger: "change" }],
        code: [
          { required: true, message: "必填", trigger: "change" },
          { min: 4, max: 4, message: "请输入4位数", trigger: "change" },
        ],
        rcode: [{ required: true, message: "必填", trigger: "change" }],
      },
    };
  },
  methods: {
    handleAvatarSuccess(res) {
      /*
      上传成功之后，由于该组件内部没有执行它的表单验证，所以我们要人为触发
      父传子（子调用父方法）
        1：在父组件标签定义ref  
        2: 拿到el-form的this===this.$refs.ref值
      */

      // this.imageUrl = res.data.file_path
      this.form.avatar = res.data.file_path;
      this.$refs.form.validateField(["avatar"]);
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg" || file.type === "image/png";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    submit() {
      this.$refs.form.validate((result) => {
        if (result) {
          getRegisterUser(this.form).then((res) => {
            console.log(res);

            // 在调用api时，只要是.then一定是200的
            // if(res.data.code == 200) {
            this.$message.success("注册成功");
            // 成功取消弹框
            this.isShow = false;
            // }
          });

          // this.$message.success("验证成功");
        } else {
          this.$message.error("验证失败");
        }
      });
    },
    // 刷新验证码
    changeCode() {
      let random = Math.random();
      this.codebase = "/captcha?type=sendsms";
      this.codebase += "&id=" + random;
    },

    // 获取手机短信验证码
    getPhoneCode() {
      let _isPass = 0;
      this.$refs.form.validateField(["phone", "code"], (errorMessage) => {
        console.log(errorMessage);
        if (errorMessage != "") {
          _isPass++;
        }
      });

      /*  调用接口获取验证码  axios： 1.装包  2. 导入  3. 使用
      验证码错误  1：验证码接口地址错误   2. 新版本谷歌浏览器使用有一定问题   3. 传递cookie到后端 （withCredentials: true）
      ajax 跨域情况cookie会通过接口传递给后端吗？   withCredentials: true
      */
     
      // axios({
      //     url: process.env.VUE_APP_URL + "/sendsms",
      //     method: "post",
      //     data: {
      //       code: this.form.code,
      //       phone: this.form.phone
      //     },
      //     withCredentials: true //跨域带cookie
      //   })
      getPhoneCodeApi({
        code: this.form.code,
        phone: this.form.phone,
      })
        .then((res) => {
          // if (res.data.code == 200) {
          this.$message.success("短信验证码：" + res.data.data.captcha + "");
          console.log(res);
          // }
          //  else {
          //   this.$message.error("获取失败");
          //   console.log(res);
          // }

          /*  为什么要把获取验证码倒计时放这里呢？
          因为验证码错误不能进去倒计时
          */
          if (_isPass == 0) {
            this.num--; // 解决延迟一秒再禁止的bug
            let timeID = setInterval(() => {
              // 自减
              this.num--;

              // 判断重启定时器
              if (this.num == 0) {
                clearInterval(timeID);
                this.num = 5;
                
                // 刷新验证码
                this.codebase = "/captcha?type=sendsms&id=" + Date.now();
              }
            }, 1000);
          }
        })
        .catch((error) => {
          console.log(error);
        });
    },
  },
  created() {
    this.baseUrl = process.env.VUE_APP_URL;
  },
};
</script>

<style lang="less">
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar-uploader {
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.register {
  .title {
    height: 53px;
    line-height: 53px;
    color: #fff;
    background: linear-gradient(to right, #01c5fa, #1394fa);
  }
  .el-dialog__header {
    padding: 0;
  }
  .code {
    width: 100%;
    height: 40px;
  }
}
</style>
